<?php
class Txy_Util_PinYin{

	public function getPinYin($str,$ishead=0,$isclose=1){
		global $pinyins;
		$restr = '';
		$str = trim($str);
		$slen = strlen($str);
		if($slen<2)
		{
			return $str;
		}
		if(count($pinyins)==0)
		{
			$fp = fopen('./pinyin.dat','r');
			while(!feof($fp))
			{
				$line = trim(fgets($fp));
				$pinyins[$line[0].$line[1]] = substr($line,3,strlen($line)-3);
			}
			fclose($fp);
		}
		for($i=0;$i<$slen;$i++)
		{
			if(ord($str[$i])>0x80)
			{
				$c = $str[$i].$str[$i+1];
				$i++;
				if(isset($pinyins[$c]))
				{
					if($ishead==0)
					{
						
						if($i<$slen-1){
							$restr .= $pinyins[$c].'-';
						}else{
							$restr .= $pinyins[$c];
						}
						
					}
					else
					{
						$restr .= $pinyins[$c][0];
					}
				}else
				{
					//$restr .= "-";
				}
			}else if(preg_match("/[a-z0-9]/i",$str[$i]) )
			{
				if($i<$slen-1){
					$restr .= $str[$i].'-';
				}else{
					$restr .= $str[$i];
				}
			}
			else
			{
				//$restr .= "-";
			}
		}
		if($isclose==0)
		{
			unset($pinyins);
		}
		return $restr;
	}
}